package com.example.demo.nacos;

import com.example.demo.utils.YamlUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * @Auther: miaoguoxin
 * @Date: 2020/3/17 20:41
 * @Description:
 */
public class NacosNamespaceLoader {

    public static void initEnv() throws IOException {
        Map<?, ?> map = YamlUtil.loadYaml("bootstrap.yml");
        Object activePro = YamlUtil.getProperty(map, "spring.profiles.active");
        Properties pro = new Properties();
        InputStream in = NacosNamespaceLoader.class.getClassLoader().getResourceAsStream("env.properties");
        pro.load(in);
        if (activePro != null && StringUtils.isNoneBlank(activePro.toString())) {
            String nacosNamespace = pro.getProperty(activePro.toString());
            if (nacosNamespace != null){
                System.setProperty("spring.cloud.nacos.discovery.namespace", nacosNamespace);
                System.setProperty("spring.cloud.nacos.config.namespace", nacosNamespace);
            }
        }
    }

    /**
    * @Description: 初始化Nacos的namespace
    * @Param:  env:环境名称，对应 env.properties ，入参ex：dev
    * @return:
    * @Author: miaoguoxin
    * @Date: 2020/3/18
    */
    public static void initEnv(String env) throws IOException {
        Properties pro = new Properties();
        InputStream in = NacosNamespaceLoader.class.getClassLoader().getResourceAsStream("env.properties");
        pro.load(in);
        String nacosNamespace = pro.getProperty(env);
        if (nacosNamespace != null){
           System.setProperty("spring.cloud.nacos.discovery.namespace", nacosNamespace);
           System.setProperty("spring.cloud.nacos.config.namespace", nacosNamespace);
       }
    }
}
